package dukeCE.InsightTracker;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;



import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;



public class postActivity extends Activity{
	
	private Button button_post,button_close;	
	private EditText field_user;	
	private EditText field_subject;	
	private EditText field_des;
	private EditText field_content;	
	private ToggleButton switchMap;

	private int showLct=0;
	private double lon=0,lat=0;
	

	   public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.post_activity);
	        
	        
	        switchMap = (ToggleButton)findViewById(R.id.switchMap);
	        LocationManager locationManager;
	        String serviceName=Context.LOCATION_SERVICE;
	        locationManager=(LocationManager)getSystemService(serviceName);
	        //String provider=LocatoinManager.GPS_PROVIDER;
	        
	        Criteria criteria=new Criteria();
	        criteria.setAccuracy(Criteria.ACCURACY_FINE);
	        criteria.setAltitudeRequired(false);
	        criteria.setBearingRequired(false);
	        criteria.setCostAllowed(true);
	        criteria.setPowerRequirement(Criteria.POWER_LOW);
	        String provider=locationManager.getBestProvider(criteria, true);
	        
	        Location location=locationManager.getLastKnownLocation(provider);
	        switchMap.setOnCheckedChangeListener(new OnCheckedChangeListener() {
	            @Override
	            public void onCheckedChanged(CompoundButton cBtn, boolean isChecked) {
	                if (isChecked == true) {
	                   showLct=1;
	                } else {
	                   showLct=0;
	                }
	            }
	        });
	        
	        findViews();	
	        
	        updateWithNewLocation(location);
	        
	        locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);  
	        setListeners();
	   }

	   private void updateWithNewLocation(Location location) {
	   	String latLongString;
	   	TextView myLocationText;
	   	myLocationText = (TextView)findViewById(R.id.myLocationText);
	   	if (location != null) {
	   	lat = location.getLatitude();
	   	lon = location.getLongitude();
	   	latLongString = "long:" + lat + "\nlat:" + lon;
	   	} else {
	   	latLongString = "cann't get GIS info";
	   	}
	   	myLocationText.setText("Topic current location:\n" +
	   	latLongString);
	   }

	   private final LocationListener locationListener = new LocationListener() {
	   	public void onLocationChanged(Location location) {
	   	updateWithNewLocation(location);
	   	}
	   	public void onProviderDisabled(String provider){
	   	updateWithNewLocation(null);
	   	}
	   	public void onProviderEnabled(String provider){ }
	   	public void onStatusChanged(String provider, int status,
	   	Bundle extras){ }
	   };

	   private void findViews()

	   {         
	       button_post = (Button) findViewById(R.id.postBt);	
	       field_user = (EditText) findViewById(R.id.usernameEt);	
	       field_content = (EditText) findViewById(R.id.contentEt);	
	       field_des = (EditText) findViewById(R.id.desEt);
	       field_subject= (EditText) findViewById(R.id.subjectnameEt);	
	       button_close = (Button) findViewById(R.id.closeBt);	

	   } 	
	   	
	   private void setListeners() 
	   {
	   	 
	   	 button_post.setOnClickListener(publist);	
	   	 button_close.setOnClickListener(goBack);
	   } 

	   private Button.OnClickListener goBack = new Button.OnClickListener()   
	   {
	   	 
	     public void onClick(View v) 
	     { 
	   	      Intent intent = new Intent();
	   	      intent.setClass(postActivity.this, Tracker02Activity.class);
	   	      startActivity(intent);


	           }
	   };
	   
	   private Button.OnClickListener publist = new Button.OnClickListener()   
	   {
	   	 
	     public void onClick(View v) 
	     { 
	   	   
	   String userStr=field_user.getText().toString();
	   String titleStr=field_subject.getText().toString();
	   String cntStr = field_content.getText().toString();
	   String desStr = field_des.getText().toString();
	   String strLocation=Integer.toString(showLct);


	   Log.e("log_tag", userStr+" "+titleStr+" "+cntStr+" "+lat+" "+lon+" ");    

	   sendMessage(userStr,titleStr,cntStr, strLocation);

	   field_user.setText("");
	   field_subject.setText("");
	   field_content.setText("");
	   field_des.setText("");
	   
	   
	      

	           }

	   private void sendMessage(String uStr, String tStr, String cStr, String loca ) {
	   	

	   	String result = "";     
//	   	String outss="";
//	   	age=etext.getText().toString();
	   	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();     
	   	nameValuePairs.add(new BasicNameValuePair("user",uStr));     
	   	nameValuePairs.add(new BasicNameValuePair("title",tStr)); 
	   	//nameValuePairs.add(new BasicNameValuePair("des",dStr)); 
	   	nameValuePairs.add(new BasicNameValuePair("content",cStr)); 
	   	nameValuePairs.add(new BasicNameValuePair("showLocation",loca));
	   	nameValuePairs.add(new BasicNameValuePair("longitude",Double.toString(lon)));
	   	nameValuePairs.add(new BasicNameValuePair("latitude",Double.toString(lat)));
	       
	   	Log.e("log_tag", uStr+" "+tStr+" "+cStr+" "+loca+" "+Double.toString(lat)+" "+Double.toString(lon)+" ");    
	   	
	   	try{
	   	     
	   	        HttpClient httpclient = new DefaultHttpClient();     
	   	        HttpPost httppost = new HttpPost("http://10.0.2.2/bbsmaptest/adr_insertM20local.php");   
	   	        //HttpPost httppost = new HttpPost("http://kevin2011.byethost3.com/adr_insertM20.php");  
	   	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));     
	   	        HttpResponse response = httpclient.execute(httppost);      
	   	        HttpEntity entity = response.getEntity();     
	   	       InputStream is = entity.getContent();     

	   	

	   	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);     
	   	        StringBuilder sb = new StringBuilder();     
	   	        String line = null;     
	   	        while ((line = reader.readLine()) != null) {     
	   	                sb.append(line + "\n");     
	   	        }     
	   	       is.close();     
	   	      
	   	       result=sb.toString();     
	   	}catch(Exception e){     
	   	        Log.e("log_tag", "Error converting result "+e.toString());     
	   	}     
	   }
	   	 };	
	   	 

	        
	        
	        
	        
	        
	        
	   }

